package org.jeecg.modules.wlhy.yunfutong.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

public class TestHttpClientUtil {
    private static HttpClient httpclient = new DefaultHttpClient();

    //生成签名
    public static Map<String, String> makeSignature(String appid, String appsecret, Long _aop_strtotime, Map<String,
            String> params) {

        //固定字段
        params.put("appid", appid);
        params.put("_aop_strtotime", String.valueOf(_aop_strtotime));

        //排序
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        //拼接签名字符串
        StringBuilder signStr = new StringBuilder();
        for (String key : keys) {
            String value = params.get(key);
            signStr.append(key).append(value);
        }

        //MD5
        signStr.append(appsecret);

        //签名不正确打印排查
        System.out.println(signStr.toString());

        String sign = stringToMD5(signStr.toString());

        params.put("_aop_signature", sign);
        return params;
    }

    //MD5
    public static String stringToMD5(String sourceStr) {
        try {
            // 获得MD5摘要算法的 MessageDigest对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(sourceStr.getBytes());
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            StringBuilder buf = new StringBuilder();
            for (int b : md) {
                int tmp = b;
                if (tmp < 0) {
                    tmp += 256;
                }
                if (tmp < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(tmp));
            }
            // return buf.toString().substring(8, 24);// 16位加密
            return buf.toString();// 32位加密
        } catch (Exception e) {
            throw new RuntimeException("没有md5这个算法！");
        }
    }

    public static void close() {
        // 关闭连接释放资源
        httpclient.getConnectionManager().shutdown();
    }

    public static String httpGet(String url) {
        String result = "";
        //httpclient = new DefaultHttpClient();
        initNetwork();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = null;
        HttpEntity entity = null;
        try {
            //ifHttps(url);
            response = httpclient.execute(httpget);
            if (response != null) {
                entity = response.getEntity();
            }

            if (entity != null) {
                try {
                    // result = new String(content.getBytes("ISO-8859-1"), "UTF-8");
                    result = EntityUtils.toString(entity);

                    // 解决HttpClient获取中文乱码 ，用String对象进行转码
                } catch (ParseException | IOException e1) {
                    e1.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close();
        }

        return result;
    }

    /**
     * POST请求
     */
    public static String httpPost(String url, HttpEntity reqEntity) {
        String result = "";
        initNetwork();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = null;
        HttpEntity entity = null;
        try {
            httppost.setEntity(reqEntity);
            httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
            response = httpclient.execute(httppost);
            if (response != null) {
                entity = response.getEntity();
            }

            if (entity != null) {
                try {
                    String content = EntityUtils.toString(entity);

                    result = new String(content.getBytes(StandardCharsets.UTF_8));
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close();
        }

        return result;
    }
    /**
     * POST请求
     */
    public static String post(String url, HttpEntity reqEntity,String token) {
        String result = "";
        initNetwork();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = null;
        HttpEntity entity = null;
        try {
            httppost.setEntity(reqEntity);
            httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httppost.setHeader("Authori-zation",token);
            response = httpclient.execute(httppost);
            if (response != null) {
                entity = response.getEntity();
            }

            if (entity != null) {
                try {
                    String content = EntityUtils.toString(entity);

                    result = new String(content.getBytes(StandardCharsets.UTF_8));
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close();
        }

        return result;
    }
    //泰信代开专用
    public static String Get(String url,String token) {
        String result = "";
        //httpclient = new DefaultHttpClient();
        initNetwork();
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("Authori-zation",token);
        HttpResponse response = null;
        HttpEntity entity = null;
        try {
            //ifHttps(url);
            response = httpclient.execute(httpget);
            if (response != null) {
                entity = response.getEntity();
            }

            if (entity != null) {
                try {
                    // result = new String(content.getBytes("ISO-8859-1"), "UTF-8");
                    result = EntityUtils.toString(entity);

                    // 解决HttpClient获取中文乱码 ，用String对象进行转码
                } catch (ParseException | IOException e1) {
                    e1.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close();
        }

        return result;
    }

    public static String doDelete(String url,String token) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpDelete httpDelete = null;
        String result = null;
        try {
            httpDelete = new HttpDelete(url);
            httpDelete.setHeader("Authori-zation",token);
            CloseableHttpResponse response = client.execute(httpDelete);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
        return result;


    }





    public static void main(String[] args) {
        Map<String,String> params =new HashMap<>();
        String appid="hnxzeeuvIm73";
        String appsecret="0ec49d56b0de3bd489bb97a915127fdd1df642ef";

        Map<String, String> sign = makeSignature(appid, appsecret, getTimeStap(), params);
        String aop_signature = sign.get("_aop_signature");
        String url="http://106.15.190.131:8100/openapi/car/ApiVehicle/add?appid="+appid+"&_aop_strtotime="+getTimeStap()+"&_aop_signature="+aop_signature;
        String s = httpPost(url,null);
        System.out.println(s);

    }

    /**
     * 初始化网络模块
     */
    private static void initNetwork() {
        try {
            // **
            SSLContext ctx = SSLContext.getInstance("TLS"); //$NON-NLS-1$
            X509TrustManager tm = new X509TrustManager() {

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] chain,
                                               String authType)
                        throws java.security.cert.CertificateException {

                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] chain,
                                               String authType)
                        throws java.security.cert.CertificateException {
                }

            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx,
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme sch = new Scheme("https", 443, ssf); //$NON-NLS-1$
            org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager tcm = new org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager();
            tcm.setMaxTotal(10);
            tcm.getSchemeRegistry().register(sch);
            httpclient = new DefaultHttpClient(tcm);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 生成10位时间戳
     * @return
     */
    public static Long getTimeStap(){
        return System.currentTimeMillis()/1000;
    }
}
